const api = require('./api')
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

/**
 * 格式化日期对象=>日期字符串
 * @param {*} date 
 * @returns 
 */
const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return `${[year, month, day].map(formatNumber).join('-')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

/**
 * 初始化账单类型列表数据
 * @param {number} type  0支出 1 收入 
 * @returns 
 */
const getBillTypes = (type) => {
  let billTypes = wx.getStorageSync("billTypes");
  if (!(billTypes && billTypes.length > 0)) {
    api.post("/billType/list", {
      "name": "",
      "level": 1
    }).then(res => {
      billTypes = res.data;
      wx.setStorageSync("billTypes", billTypes);
    })
  }
  // 根据 type进行过滤
  if (type != undefined) {
    billTypes = billTypes.filter(bt => bt.type == type);
  }
  return billTypes;
}

/**
 * 判断对象是否为空
 * @param obj 
 * @returns 
 */
function isEmpty(obj) {
  // 数字判空
  if (isNumber(obj)) {
    return false;
  }
  // 字符串和数组判空
  if (obj && obj.length > 0) {
    return false;
  }
  return true;
}

/**
 * 判断是否为数字
 * @param obj 
 * @returns 
 */
function isNumber(obj) {
  if (parseFloat(obj).toString() == "NaN") {
    return false;
  }
  return true;
}

/**
  * 删除数组中指定对象
  * @param {OBject} arr 
  * @param {function} func 返回ture或false
  */
function arrDelete(arr, func) {
  // 遍历取到每个对象和对应下标，通过自定义的函数判断该对象是否删除，
  arr.forEach((item, i) => {
    if (func(item)) {
      arr.splice(i, 1)
    }
  })
}

module.exports = {
  formatTime,
  formatDate,
  getBillTypes,
  isEmpty,
  isNumber,
  arrDelete
}
